package liuru.world.observation.controller.observability.metric;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import liuru.world.observation.controller.constant.MetricConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.HashMap;
import java.util.Map;

@Component
public class ScheduleTaskCounter {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleTaskCounter.class);

    private final Map<String, Counter> counters;

    public ScheduleTaskCounter() {
        counters = new HashMap<>();
        initializeCounters();
    }

    private void initializeCounters() {
        // 使用MetricConstants中的常量来初始化计数器
        for (String type : MetricConstants.SCHEDULE_TASK_TYPES) {
            if (type.isBlank()) {
                logger.error("MetricConstants.SCHEDULE_TASK_TYPES含有非法文件类型：{}", type);
                continue;
            }
            for (String status : MetricConstants.SCHEDULE_TASK_STATUSES){
                if (status.isBlank()) {
                    logger.error("MetricConstants.SCHEDULE_TASK_STATUSES含有非法文件状态：{}", status);
                    continue;
                }
                try{
                    counters.put(
                            type + "_" + status,
                            Counter.builder(MetricConstants.SCHEDULE_TASK_TOTAL)
                                    .tags(MetricConstants.TYPE, type,MetricConstants.STATUS,status)
                                    .description("定时任务数（标签：任务类型-type，状态-status）")
                                    .register(Metrics.globalRegistry)
                    );
                }catch (Exception e){
                    logger.error("该定时任务注册指标失败：类型-{}，状态-{}，错误信息：{}", type,status, e.getMessage(),e);
                }
            }
        }
    }

    public void increment(String type, String status) {
        Assert.notNull(counters.get(type + "_" + status),"定时任务总数Map不能为空");
        counters.get(type + "_" + status).increment();
    }

}
